//
//  FocusView.swift
//  DYSwiftFramework
//
//  Created by huangdeyu on 2021/10/29.
//  Copyright © 2021 none. All rights reserved.
//

import UIKit
import SwiftyJSON

class FocusView: BaseTableView {
    
//   lazy var player:VideoPlayer = VideoPlayer();

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    init() {
        super.init(pageIndex: 0, pageSize: 10)
        tableView.snp.remakeConstraints { (mak) in
            mak.left.bottom.right.equalToSuperview()
            mak.top.equalToSuperview().offset(NAV_HEIGHT)
        }
        tableView.register(FocusCell.self, forCellReuseIdentifier: "cell")
        self.onLoad = { [weak self] (index) in
            self?.load()
        }
        load()
    }
    
    func load() {
        HTTP.get(url: FoundApi.focusList, parms: [
            "version":10,
            "pageIndex":pageIndex,
            "pageSize":pageSize
        ]).response { [weak self] (data, error) in
            if let _ = error {
            } else {
                let model = DDFocusListModel.init(json: data as? [String:Any?])
                self?.dealWith(data: model?.recList, error: error)
            }
        }
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? FocusCell,
           let item = models[indexPath.row] as? RecList{
            item.cellIndex = indexPath.row
            cell.loadData(item: item)
            return cell
        }
       
        return UITableViewCell.init()
    }
    
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        findCurrentCell()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate {
            findCurrentCell()
        }
    }
    
    func findCurrentCell()  {
        for cell in tableView.visibleCells {
            if cell is FocusCell{
               let focusCell = cell as! FocusCell;
               if let _ = focusCell.model?.videoUrl {
                   let rect = focusCell.videoView.convert(cell.bounds, to: self)
                   let inInset = self.tableView.frame.contains(rect)
                   // dang qian shi pin zai ke shi hua qujian
                   if inInset {
                        self.models.forEach { (cellModel) in
                            if (cellModel is RecList) {
                                (cellModel as! RecList).isTheOne = false;
                            }
                        }
                        focusCell.model?.isTheOne = true;
//                        player.startPlay(url: focusCell.model!.videoUrl!, onView: focusCell.videoView);
                        break
                   }
               }
               
            }
        }
    }
}
